package Socket;

import java.io.*;
import java.net.Socket;

/**
 * Created by sunwei on 2017/9/29
 * Time:14:00
 */
//服务器端响应请求的线程类
public class ServerSocketThread extends Thread{
    private Socket socket = null;//定义客户端套接字
    private BufferedReader bufferedReader = null;//定义缓冲字符流来读取数据
    private PrintWriter printWriter = null;//定义输出写入流

    //声明构造函数,用来接受客户端的socket套接字
    public ServerSocketThread(Socket socket){
        this.socket =socket;
    }

    @Override
    public void run() {
        try {
            //注意此处得到的socket的输入流为socket的输入流即上方的（private Socket socket = null）
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //向客户端返回消息的PrintWrite对象
            printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
            String str = bufferedReader.readLine();//将读入的数据按行读取，放到一个字符串变量里面
            System.out.println("Client Socket Message:"+str);//打印这个字符串
            printWriter.println("Message Received");
            printWriter.flush();//刷新输出流
        } catch (Exception e) {
            try {
                bufferedReader.close();
                printWriter.close();
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }finally {

        }

    }
}
